package com.example.zhuiwei.springbootbase.config;

import com.example.zhuiwei.springbootbase.filter.MyFilter;
import com.example.zhuiwei.springbootbase.listener.MyListener;
import com.example.zhuiwei.springbootbase.servlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class MyServletConfig {


    /**
     * 注册servlet
     * 指定请求的路劲，当请求为localost:8080/myServlet。执行MyServlet中doPost或getPost方法
     */
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        //设置启动顺序
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    /**
     * 注册拦截器
     * 可以指定filter拦截哪些请求，拦截会执行执行MyFilter类中的doFilter方法
     */
    @Bean
    public FilterRegistrationBean myFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
        return registrationBean;
    }

    /**
     * 注册拦截器监听器
     *
     */
    @Bean
    public ServletListenerRegistrationBean myListener(){
        ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }


//    //此处配置嵌入式的Servlet容器，如端口参数，这只是一种配置方式；另外一种就是在application中配置如server.port=8083
//    @Bean
//    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
//        return new EmbeddedServletContainerCustomizer() {
//
//            //定制嵌入式的Servlet容器相关的规则
//            @Override
//            public void customize(ConfigurableEmbeddedServletContainer container) {
//                container.setPort(8083);
//            }
//        };
//    }
}
